//
//  YBTransferCoinsViewController.m
//  Nectar
//
//  Created by famer on 2023/11/12.
//  Copyright © 2023 asance. All rights reserved.
//

#import "YBTransferCoinsViewController+LayoutConstraints.h"
#import "YBTransferCoinTableViewCell.h"
#import "YBTransferViewController.h"
#import "HomeCoinManager.h"

@interface YBTransferCoinsViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(strong, nonatomic) NSMutableArray *dataSource;
@property(strong, nonatomic) NSMutableArray *originDataSource;

@end

@implementation YBTransferCoinsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kWhiteColor;
    
    [self.view addSubview:self.selectAssetLabel];
    [self.view addSubview:self.assetLabel];
    [self.view addSubview:self.backImageView];
    [self.view addSubview:self.backButton];

    [self.view addSubview:self.searchContentView];
    [self.searchContentView addSubview:self.searchImageView];
    [self.searchContentView addSubview:self.searchTextField];

    [self.view addSubview:self.myTableView];

    [self updateUI];
    [self setLayoutConstraints];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getCoins];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"YBTransferCoinTableViewCell";
    YBTransferCoinTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    [cell setData:self.dataSource[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RevDataGetCoins *data = [self.dataSource objectAtIndex:indexPath.row];
    
    [self toTransferViewController:data.coinType];
}

#pragma mark - Private Method
- (void)updateUI{
    self.searchContentView.clipsToBounds = YES;
    self.searchContentView.layer.cornerRadius = 6;
    
    self.backImageView.contentMode = UIViewContentModeScaleAspectFit;
        
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onTextFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
}

- (void)onGoBackAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getCoins{
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    NSString *urlString = [NSString stringWithFormat:@"%@",YB_URL_GET_COINS];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"getCoins: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            NSArray *coinsArray = [RevDataGetCoins mj_objectArrayWithKeyValuesArray:obj.data];
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:coinsArray];
            
            [self.originDataSource removeAllObjects];
            [self.originDataSource addObjectsFromArray:coinsArray];
            [self.myTableView reloadData];
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}


#pragma mark - Notification
- (void)onTextFieldTextDidChangeNotification:(NSNotification *)notification{
    @synchronized (self) {
        NSString *searchValue = self.searchTextField.text;
        NSLog(@"search value: %@", searchValue);
        
        [self.dataSource removeAllObjects];
        if(searchValue==nil || searchValue.length==0){
            [self.dataSource addObjectsFromArray:self.originDataSource];
            [self.myTableView reloadData];
            
        } else{
            searchValue = [searchValue lowercaseString];
            
            for(int i=0;i<self.originDataSource.count;i++){
                RevDataGetCoins *data = self.originDataSource[i];
                if([[data.coinName lowercaseString] containsString:searchValue]){
                    [self.dataSource addObject:data];
                    
                } else if([[data.name lowercaseString] containsString:searchValue]){
                    [self.dataSource addObject:data];
                }
            }
        }
        
        [self.myTableView reloadData];
    }
}

- (void)toTransferViewController:(NSString *)coinType{
    YBTransferViewController *viewcontroller = [[YBTransferViewController alloc] init];
    viewcontroller.coinType = coinType;
    viewcontroller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}

#pragma mark - Getter Setter
YBLabelGetter(selectAssetLabel, _selectAssetLabel, [UIFont systemFontOfSize:18], @"Select Asset", kThemeBlackColor, NSTextAlignmentCenter);
YBLabelGetter(assetLabel, _assetLabel, [UIFont systemFontOfSize:14], [HomeCoinManager shareInstance].globalName, kThemeHintColor, NSTextAlignmentCenter);

YBImageViewGetter(backImageView, _backImageView, [UIImage imageNamed:@"icon_nav_back"]);
YBImageViewGetter(searchImageView, _searchImageView, [UIImage imageNamed:@"icon_input_search"]);

YBViewGetter(searchContentView, _searchContentView, [UIColor hexColor:@"F4F5F7"])

- (UIButton *)backButton{
    if(!_backButton){
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backButton.backgroundColor = [UIColor clearColor];
        _backButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_backButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateHighlighted];
        [_backButton setTitle:@"" forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(onGoBackAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UITextField *)searchTextField{
    if(!_searchTextField){
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.borderStyle = UITextBorderStyleNone;
        _searchTextField.backgroundColor = kClearColor;
        _searchTextField.keyboardType = UIKeyboardTypeDefault;
        _searchTextField.returnKeyType = UIReturnKeyDone;
        _searchTextField.font = [UIFont systemFontOfSize:12];
        _searchTextField.placeholder = @"Input Token Name";
        _searchTextField.textColor = kThemeBlackColor;
        _searchTextField.delegate = self;
    }
    return _searchTextField;
}

- (UITableView *)myTableView{
    if(!_myTableView){
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _myTableView.backgroundColor = [UIColor whiteColor];
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        [_myTableView registerClass:[YBTransferCoinTableViewCell class] forCellReuseIdentifier:@"YBTransferCoinTableViewCell"];
    }
    return _myTableView;
}

- (NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (NSMutableArray *)originDataSource{
    if(!_originDataSource){
        _originDataSource = [[NSMutableArray alloc] init];
    }
    return _originDataSource;
}


@end
